package com.kim.rssreader.db;

import java.util.HashMap;
import java.util.Map.Entry;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.kim.rssreader.domain.constant.RssCategoryConstant;
import com.kim.rssreader.domain.constant.RssColumnConstant;
import com.kim.rssreader.domain.constant.RssContentConstant;

public class DBUtils {

	public static final String TAG = "DBUtils";

	private static final byte[] LOCK = new byte[1];

	private static final String DBNAME = "rss.db";
	// private static final int DBVERSION = 1;
	private static final int DBVERSION = 2;

	private static BaseDBHelper dbHelper;
	private Context context;

	private SQLiteDatabase database;

	public DBUtils(Context context) {
		this.context = context;
		if (dbHelper == null) {
			dbHelper = new BaseDBHelper(this.context, DBNAME, null, DBVERSION);
		}
	}

	public void openReadableDatabase() {
		synchronized (LOCK) {
			database = dbHelper.getReadableDatabase();
		}
	}

	public void openWriteableDatabase() {
		synchronized (LOCK) {
			database = dbHelper.getWritableDatabase();
		}
	}

	public void closeDB() {
		synchronized (LOCK) {
			database.close();
		}
	}

	// 清除所有数据
	public void trunkData() {
		// 清除所有数据
		synchronized (LOCK) {
			try {
				openWriteableDatabase();
				database.beginTransaction();
				executeSql("delete from " + RssCategoryConstant.TABLE_NAME,
						null);
				executeSql("delete from " + RssColumnConstant.TABLE_NAME, null);
				executeSql("delete from " + RssContentConstant.TABLE_NAME, null);
				// select * from sqlite_sequence;
				// update sqlite_sequence set seq=0 where name='表名';
				executeSql("update sqlite_sequence set seq=0 ", null);

				database.setTransactionSuccessful();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				database.endTransaction();
			}
		}
	}

	/**
	 * 恢复数据到初始状态
	 */
	public void resumeData() {
		// 清除所有数据
		synchronized (LOCK) {
			try {
				openWriteableDatabase();
				database.beginTransaction();
				DataFactory.generateBuildinCategoryData(database);
				DataFactory.generateBuildinColumnData(database);
				database.setTransactionSuccessful();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				database.endTransaction();
			}
		}
	}

	public void insertDataBatch(String[] sqls) {
		String sqlLog = null;
		synchronized (LOCK) {
			try {
				database.beginTransaction();
				for (String sql : sqls) {
					sqlLog = sql;
					if (sqlLog == null || "null".equalsIgnoreCase(sqlLog)) {
						continue;
					}
					database.execSQL(sql);
				}
				database.setTransactionSuccessful();
			} catch (Exception e) {
				Log.e(TAG, "执行该SQL出错：：" + sqlLog);
				e.printStackTrace();
			} finally {
				database.endTransaction();
			}
		}
	}

	/**
	 * 插入数据
	 * 
	 * @param table
	 * @param contentValues
	 */
	public void insertData(String table, ContentValues contentValues) {
		synchronized (LOCK) {
			try {
				database.insert(table, null, contentValues);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
			}
		}
	}

	/**
	 * 读取数据
	 * 
	 * @param table
	 * @param columns
	 * @param selection
	 * @param selectionArgs
	 * @param groupBy
	 * @param having
	 * @param orderBy
	 * @return
	 */
	public Cursor checkData(String table, String[] columns, String selection,
			String[] selectionArgs, String groupBy, String having,
			String orderBy) {
		synchronized (LOCK) {
			try {
				return database.query(table, columns, selection, selectionArgs,
						groupBy, having, orderBy);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {

			}
		}
		return null;
	}

	/**
	 * 更新数据
	 * 
	 * @param table
	 * @param values
	 * @param whereClause
	 * @param whereArgs
	 * @return
	 */
	public int updateData(String table, ContentValues values,
			String whereClause, String[] whereArgs) {
		synchronized (LOCK) {
			try {
				int result = database.update(table, values, whereClause,
						whereArgs);
				return result;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
			}
		}
		return -1;
	}

	/**
	 * 批量更新数据
	 * 
	 * @param table
	 * @param contentValues
	 * @param whereClause
	 * @return
	 */
	public int updateDataBatch(String table,
			HashMap<String, ContentValues> contentValues, String whereClause) {
		synchronized (LOCK) {
			try {
				int result = 0;
				for (Entry<String, ContentValues> contentValue : contentValues
						.entrySet()) {
					result += database
							.update(table, contentValue.getValue(),
									whereClause,
									new String[] { contentValue.getKey() });
				}
				return result;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
			}
		}
		return -1;
	}

	/**
	 * 执行SQL语句
	 * 
	 * @param sql
	 * @param bindArgs
	 */
	public void executeSql(String sql, String[] bindArgs) {
		synchronized (LOCK) {
			database.execSQL(sql, bindArgs);
		}
	}

	/**
	 * 执行查询语句
	 * 
	 * @param sql
	 * @param selectionArgs
	 * @return
	 */
	public Cursor rowQuery(String sql, String[] selectionArgs) {
		synchronized (LOCK) {
			return database.rawQuery(sql, selectionArgs);
		}
	}

	/**
	 * 获取int类型数据
	 * 
	 * @param cursor
	 * @param columnIndex
	 * @return
	 */
	public int getInt(Cursor cursor, int columnIndex) {
		return cursor.getInt(columnIndex);
	}

	/**
	 * 获取String类型数据
	 * 
	 * @param cursor
	 * @param columnIndex
	 * @return
	 */
	public String getString(Cursor cursor, int columnIndex) {
		return cursor.getString(columnIndex);
	}

	/**
	 * 获取boolean类型数据
	 * 
	 * @param cursor
	 * @param columnIndex
	 * @return
	 */
	public boolean getBoolean(Cursor cursor, int columnIndex) {
		return (cursor.getInt(columnIndex) == 0 ? false : true);
	}

}
